#include <iostream>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
#include "mutex.hpp"

#define NUM 4

int tickets=1000;//用多线程,模拟一轮抢票

pthread_mutex_t lock =PTHREAD_MUTEX_INITIALIZER;//-----全局锁

class threadData
{
public:
    threadData(int number,pthread_mutex_t * mutex)
    {
        threadname="thread"+to_string(number);
        lock=mutex;
    }

    
public:
    string threadname;
    pthread_mutex_t * lock;
};

void* getTicket(void* args)
{
    threadData* td =static_cast<threadData*>(args);
    const char* name=td->threadname.c_str();
    while(true)
    {
        {//------------------------------------------
            //tickets临界资源------临界区
            LockGuard lockguard(&lock);//创建lockguard临时变量,RAII风格的锁
            if(tickets>0)
            {
                usleep(1000);
                printf("who=%s,get a ticket: %d\n",name,tickets);
                tickets--;
            }
            else
            {
                break;
            }
        }//--------------------------------------------
        usleep(13);//--平衡
    }
    printf("%s ... quit\n",name);
    return nullptr;
}

int main()
{
    pthread_mutex_t lock;//----定义锁
    pthread_mutex_init(&lock,nullptr);//---------初始化锁

    vector<pthread_t> tids;
    vector<threadData*> thread_datas;
    for(int i=1;i<NUM;i++)
    {
        pthread_t tid;
        threadData* td =new threadData(i,&lock);//---------???
        thread_datas.push_back(td);
        pthread_create(&tid,nullptr,getTicket,thread_datas[i-1]);
        tids.push_back(tid);
    }

    for(auto thread : tids)
    {
        pthread_join(thread,nullptr);
    }
    for(auto td:thread_datas)
    {
        delete td;
    }

    pthread_mutex_destroy(&lock);//-------------释放
    return 0;
}









// void* getTicket(void* args)
// {
//     threadData* td =static_cast<threadData*>(args);
//     const char* name=td->threadname.c_str();
//     while(true)
//     {
//         //tickets临界资源------临界区
//         pthread_mutex_lock(td->lock);//------加锁
//         if(tickets>0)
//         {
//             usleep(1000);
//             printf("who=%s,get a ticket: %d\n",name,tickets);
//             tickets--;
//             pthread_mutex_unlock(td->lock);//-----解锁
//         }
//         else
//         {
//             pthread_mutex_unlock(td->lock);//-----解锁
//             break;
//         }
//         usleep(13);//-------------------平衡
//     }
//     printf("%s ... quit\n",name);
//     return nullptr;
// }